import {constantRouterMap} from '@/router/index'
import Layout from '@/views/layout/Layout'


// 对菜单进行排序
function sortRouters(accessedRouters) {
  for (let i = 0; i < accessedRouters.length; i++) {
    let router = accessedRouters[i]
    if (router.children && router.children.length > 0) {
      router.children.sort(compare('sort'))
    }
  }
  accessedRouters.sort(compare('sort'))
}

// 降序比较函数
function compare(p) {
  return function (m, n) {
    let a = m[p]
    let b = n[p]
    return b - a
  }
}

function fetchAllResource(menus, allResource) {
  let menusArr = menus || []
  menusArr.forEach(m => {
    if (m.perm) {
      allResource.push(m.perm)
    }
    if (m.children && m.children.length > 0) {
      fetchAllResource(m.children, allResource)
    }
  })
}

function loadView(view) { // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}

function genRouterFromServer(serverRouter, parent) {
  if (!serverRouter || serverRouter.length <= 0) {
    return [];
  }
  // 菜单类型（1：菜单，2：目录，3：外链，4：按钮）
  serverRouter.forEach(m => {
    if (m.type === '2') {
      var currentParentChildren = []
      var currentParent = {
        path: m.path,
        component: Layout,
        meta: {title: m.name, icon: m.icon, resources: m.perm},
        hidden: m.visible === '0',
        children: currentParentChildren
      }
      parent.push(currentParent)
      if (m.children && m.children.length > 0) {
        genRouterFromServer(m.children, currentParentChildren)
      }
    } else if (m.type === '1') {
      let path = m.path
      if (path.startsWith("/")) {
        path = path.substring(1)
      }
      var currentMenu = {
        path: path,
        component: loadView(m.component),
        meta: {title: m.name, icon: m.icon, resources: m.perm},
        hidden: m.visible === '0'
      }
      parent.push(currentMenu)
    }
  })

}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    allResource: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    SET_ALL_RESOURCE: (state, allResource) => {
      state.allResource = allResource
    }
  },
  actions: {
    GenerateRoutes({commit}, data) {
      return new Promise(resolve => {
        const {menus} = data

        const allResource = [];
        fetchAllResource(menus, allResource)
        commit('SET_ALL_RESOURCE', allResource)

        const serverRouterAfterProcess = [];
        genRouterFromServer(menus, serverRouterAfterProcess)
        const accessedRouters = serverRouterAfterProcess

        // 对菜单进行排序
        sortRouters(accessedRouters)
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission